package com.zjy.org.service.impl;

import com.zjy.basic.commonenum.ErrorCode;
import com.zjy.basic.constant.Constant;
import com.zjy.basic.domain.vo.ShopStatisticsVo;
import com.zjy.basic.exception.CustomException;
import com.zjy.basic.util.AjaxResult;
import com.zjy.basic.util.BaiduAuditUtils;
import com.zjy.org.domain.Employee;
import com.zjy.org.domain.Shop;
import com.zjy.org.domain.ShopAuditLog;
import com.zjy.org.mapper.EmployeeMapper;
import com.zjy.org.mapper.ShopAuditLogMapper;
import com.zjy.org.mapper.ShopMapper;
import com.zjy.org.service.ShopService;
import com.zjy.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements ShopService {
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;
    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 注册
     * @param shop
     */
    @Override
    @Transactional
    public void settlement(Shop shop) {
        //参数校验 spring validation
        //校验两次密码是否一致
        if (!shop.getManager().getPassword().equals(shop.getManager().getComfirmPassword())) {
            throw new CustomException("两次密码不一致！");
        }
        //校验店铺是否注册过
        Shop shop1 = shopMapper.findByName(shop.getName());
        if (shop1 != null) {
            throw new CustomException("该店铺已被注册！");
        }
        //校验：百度AI文本审核
        Boolean auditFlag = false;
        auditFlag = BaiduAuditUtils.TextCensor(shop.getName());
        //图片审核
        if (shop.getLogo() != null) {
            auditFlag = BaiduAuditUtils.ImgCensor(Constant.IMG_SHOW_URL + shop.getLogo());// 471/grop/sasdfasdf.jpg
        }
        //如果出现不合规内容，则抛出业务异常
        if (!auditFlag) {
            throw new CustomException(ErrorCode.CONTENT_AUDIT_FAILED.getCode());
        }

        //初始化店铺状态和注册时间（这一步在domain设置了默认值）
        //保存店铺
        shopMapper.add(shop);

        //校验店长是否注册
        Employee employee = employeeMapper.findByUsername(shop.getManager().getUsername());
        System.out.println(employee);
        //店长如果注册过是否是别的店铺的
        if (employee != null && employee.getShop_id() != null) {
            throw new CustomException("该店长已被注册！");
        }
        //如果店长存在但是没有shopid就直接绑定本次shop的id
        if (employee != null) {
            //员工有，并且可以成为这次的店长
            employee.setShop_id(shop.getId());
            shop.setAdminId(employee.getId());
        } else {//如果店长不存在
            employee = shop.getManager();
            employee.setShop_id(shop.getId());
            //先添加店长到数据库中
            employeeMapper.add(employee);
            //再给店铺绑定这个店长
            shop.setAdminId(employee.getId());
        }
        //更新店铺
        shopMapper.update(shop);
    }

    /**
     * 审核通过
     *
     * @param log
     */
    @Override
    @Transactional
    public void pass(ShopAuditLog log) throws MessagingException {
        //先设置店铺状态为待激活
        shopMapper.updateState(log.getShopId(),2);

        //设置审核日志状态 1通过0驳回
        log.setState(1);
        //设置审核人（以后做成动态的）
        log.setAuditId(333L);
        //添加审核信息
        shopAuditLogMapper.add(log);

        //发送邮件：告诉店铺管理员激活邮件使用
        //创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //发送复杂邮件的工具类
        //true - 能够添加附件
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
        helper.setFrom("1432346052@qq.com");
        helper.setSubject("店铺激活邮件");
        //true - 能够再内容中编写html标签 - 会解析
        Shop shop = shopMapper.findById(log.getShopId());
        helper.setText("<h1>你的店铺已经注册!!!</h1><img src='http://123.207.27.208"+shop.getLogo()
                        +"' ><a href='http://127.0.0.1:8080/shop/active/"+shop.getId()+"'>点击该链接激活</a>",
                true);
        Employee employee = employeeMapper.findById(shop.getAdminId());
        //收件人
        helper.setTo(employee.getEmail());
        javaMailSender.send(mimeMessage);

//        //查询店长
//        Employee emp = employeeMapper.loadOne(shop.getAdminId());
//        //发送激活邮件
//        SimpleMailMessage sm = new SimpleMailMessage();
//        //发件人
//        sm.setFrom("hm3761176@vip.qq.com");
//        //收件人
//        sm.setTo(emp.getEmail());
//        //标题
//        sm.setSubject("宠物乐园激活邮件");
//        //内容
//        sm.setText("http://localhost:8080/shop/active/"+shop.getId());
//        javaMailSender.send(sm);
    }

    /**
     * 审核驳回
     *
     * @param log
     */
    @Override
    @Transactional
    public void reject(ShopAuditLog log) {
        //修改店铺和(店长的状态应该再激活店铺的时候改为正常状态)
        Shop shop = shopMapper.findById(log.getShopId());
        shop.setState(-1);//修改店铺为待激活状态
        shopMapper.update(shop);

        //设置审核日志状态 1通过0驳回
        log.setState(0);
        //设置审核人（以后做成动态的）
        log.setAuditId(333L);
        //添加审核信息
        shopAuditLogMapper.add(log);

//        //查询店长
//        Employee emp = employeeMapper.loadOne(shop.getAdminId());
//        //发送激活邮件
//        SimpleMailMessage sm = new SimpleMailMessage();
//        //发件人
//        sm.setFrom("hm3761176@vip.qq.com");
//        //收件人
//        sm.setTo(emp.getEmail());
//        //标题
//        sm.setSubject("宠物乐园驳回邮件");
//        //内容
//        sm.setText("http://localhost:8081/#/regiter2?id="+shop.getId());
//        javaMailSender.send(sm);
    }

    /**
     * echarts报表
     * @return
     */
    @Override
    public AjaxResult statistics() {
        List<Integer> x = new ArrayList<>();
        List<Integer> xValue = new ArrayList<>();
        //查询统计的数据
        List<ShopStatisticsVo> echarts = shopMapper.statistics();
        //把x轴的值装在一个集合，把xValue装在一个集合
        for (ShopStatisticsVo echart : echarts) {
            x.add(echart.getState());
            xValue.add(echart.getCount());
        }
        //封装HashMap表示x轴的集合以及x对应值的集合
        HashMap map = new HashMap<String,List<Integer>>();
        map.put("x",x);
        map.put("xValue",xValue);

        return AjaxResult.me().setResultObj(map);
    }

    @Override
    public void adtive(Shop shop) {
        //把状态设置为"审核通过"
        shopMapper.updateState(shop.getId(),1);
        Employee employee = employeeMapper.findById(shop.getAdminId());
        employee.setState(1);
        //更新店铺信息
        employeeMapper.update(employee);
    }

}
